import 'dart:async';

import 'package:cher_flare/routes/app_pages.dart';
import 'package:cher_flare/utils/app_color.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class LYGuidePage extends StatefulWidget {
  const LYGuidePage({super.key});

  @override
  State<LYGuidePage> createState() => _LYGuidePageState();
}

class _LYGuidePageState extends State<LYGuidePage> {
  final pageController = PageController();
  Timer? _timer;
  int seconds = 8;

  @override
  void initState() {
    super.initState();
    createTimer();
  }

  void _pageChanged(int index) {
    _cancelTimer();
    seconds = 2;
    createTimer();
  }

  void createTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      seconds -= 1;
      debugPrint("===$seconds");
      if (seconds == 0) {
        final currentPage = pageController.page ?? 0;
        if (currentPage < 2) {
          final page = currentPage + 1;
          pageController.jumpToPage(page.toInt());
        } else {
          Get.offAllNamed(AppPages.login);
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView(
        controller: pageController,
        onPageChanged: (index) {
          _pageChanged(index);
        },
        children: [
          _makeItem('guide_0.png'),
          _makeItem('guide_1.png'),
          _makeItem('guide_2.png'),
        ],
      ),
    );
  }

  Widget _makeItem(String imgName) {
    return InkWell(
      onTap: () {
        _cancelTimer();
        final currentPage = pageController.page ?? 0;
        if (currentPage >= 2) {
          Get.toNamed(AppPages.login);
        } else {
          final page = currentPage + 1;
          pageController.jumpToPage(page.toInt());
        }
      },
      child: Image.asset(
        'assets/images/$imgName',
        fit: BoxFit.cover,
      ),
    );
  }

  void _cancelTimer() {
    _timer?.cancel();
    _timer = null;
  }

  @override
  void dispose() {
    _cancelTimer();
    super.dispose();
  }
}
